<?php

/**
 * Created by PhpStorm.
 * Author: ls
 * Time: 2023/8/25 14:23
 * Desc: 二维码处理
 */
class St_Qrcode
{

    /**
     * 创建二维码base64
     * @param $share_url
     * @return string
     */
    public static function ceate_code($share_url)
    {
        $root = dirname(dirname(dirname(dirname(__FILE__))));
        require_once $root . "/res/vendor/qrcode/phpqrcode.php";
        $errorCorrectionLevel = "Q";
        $matrixPointSize      = 4;
        QRcode::png($share_url, false, $errorCorrectionLevel, $matrixPointSize);
        $imageString = base64_encode(ob_get_contents());
        ob_end_clean();
        return "data:image/png;base64," . $imageString;
    }

    /**
     * 获取二维码地址
     * @param $share_url
     * @param $path
     * @param $filename
     * @return false|string
     * @throws Kohana_Exception
     */
    public static function get_code_url($share_url, $path, $filename)
    {
        $base64_image_content = St_Qrcode::ceate_code($share_url);
        //匹配出图片的格式
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)) {
            // 图片后缀
            $type = $result[2];
            // 根目录
            $dir = rtrim(BASEPATH . '/', '\\../');
            // 存放文件夹
            $new_file = $dir;
            // 循环查询文件是否存在
            $fileArr = explode('/', $path);
            foreach ($fileArr as $fileV) {
                if ($fileV) {
                    $new_file .= '/' . $fileV;
                    if (!file_exists($new_file)) {
                        //检查是否有该文件夹，如果没有就创建
                        mkdir($new_file, 0777);
                    }
                }
            }

            // 图片名
            $filename = $filename ?: time() . rand('100000', '999999');
            $img      = $filename . ".{$type}";

            $new_filename = $new_file . '/' . $img; // 文件存放位置
            $resUrl       = $path . $img; // 保存成功后返回全路径
            // 检查文件是否存在
            if (file_exists($new_filename)) {
                //检查是否有该文件夹，如果没有就创建
                return $resUrl;
            }

            // 保存文件
            if (file_put_contents($new_filename, base64_decode(str_replace($result[1], '', $base64_image_content)))) {
                $config = Kohana::$config->load('image');
                foreach ($config as $k => $item) {
                    if (is_array($item) && $item['is_open'] && method_exists($item['callback'], 'move_image')) {
                        $value = $item['callback']::move_image($item, $resUrl);
                        if ($value) {
                            $resUrl = '/' . $value;
                        }
                    }
                }
                return $resUrl;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }
}